import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Vue from 'vue'
import router from '@/router';

// create an axios instance
const service = axios.create({
  baseURL: 'http://49.4.85.96' // url = base url + request url
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if (config.loading) {
    //   Vue.prototype.$startLoading()
    // }
    if (getToken()) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // Vue.prototype.$endLoading()
    console.log(response)
    const res = response.data
    if (res.code === 200) {
      return res
    } else if (res.code === 401) {
      router.replace('/login')
      return
    } else {
      Message.error(res.msg)
    }
    return Promise.reject(res.msg)
  },
  error => {
    Vue.prototype.$endLoading()
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

const get = (url, params = {}, loading = false) => service({
  method: 'get',
  url,
  params,
  loading
})
const post = (url, params, data, loading = true) => service({
  method: 'post',
  url,
  params,
  data,
  loading
})
const postFile = (url, data) => service({
  method: 'post',
  url,
  data,
  headers: {
    'Content-type': 'multipart/form-data'
  }
})
const put = (url, params, data, loading = true) => service({
  method: 'put',
  url,
  params,
  data,
  loading
})

const del = (url, params, data, loading = true) => service({
  method: 'delete',
  url,
  params,
  data,
  loading
})

export {
  get,
  post,
  postFile,
  put,
  del
}
export default service
